package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.dto.LoginUser;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service(value = "userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    /**
     *
     * 用户登录
     * @return
     */
    @Override
    public JsonResult userLogin(User user) {
        Authentication authentication = null;
        //账号 密码验证  该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        try {
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUserId(),user.getUserPassword()));
        } catch (Exception e) {
            return ResultUtil.fail("账号,或密码错误");
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String encodePassword = bCryptPasswordEncoder.encode(user.getUserPassword());
        loginUser.setPassword(encodePassword);

        String jwtToken = TokenUtil.getJwtToken(user.getUserId());
        //登录成功 刷新redis数据
        redisUtil.setCacheObject(user.getUserId(),loginUser);
        Map<String,Object> map = new HashMap<>();
        map.put("token", jwtToken);
        return ResultUtil.success("登录成功",map);
    }

    @Override
    public JsonResult userExit(HttpServletRequest httpServletRequest) {
        String id = TokenUtil.getTokenUsername(httpServletRequest);
        if(CheckUtil.checkObject(id)){
            return ResultUtil.fail("退出失败");
        }
        redisUtil.removeCache(id);
        return ResultUtil.success("退出成功");
    }
}
